import axios from 'axios'
// import {decode} from 'vue-router/src/util/query'
//
const service = axios.create({ // 定义一个默认的响应的类型
    responseType: 'arraybuffer'
})

service.interceptors.request.use(config => {
    config.headers['Authorization'] = localStorage.getItem('token')
    return config
}, error => {
    console.log(error)
})

service.interceptors.response.use(resp => {
    const headers = resp.headers
    let reg = RegExp(/application\/json/) // 定义正则表达式
    if (headers['content-type'].match(reg)) {
        resp.data = unitToString(resp.data)
    } else {
        let fileDownload = require('js-file-download') // 插件
        let fileName = headers['content-disposition'].split(';')[1].split('filename=')[1] // 文件名
        let contentType = headers['content-type'] // 响应类型
        fileName = decodeURIComponent(fileName)  // 文件名格式的转换，防止乱码
        fileDownload(resp.data, fileName, contentType)
    }
}, error => {
    console.log(error)
})

function unitToString(unitArray) { // 主要处理json格式的转换
    let encodedString = String.fromCharCode.apply(null, new Uint8Array(unitArray))
    let decodedString = decodeURIComponent(escape(encodedString))
    return JSON.parse(decodedString)
}

let base = ''
export const downloadRequest = (url, params) => {
    return service({
        method: 'get',
        url: `${base}${url}`,
        data: params
    })
}

export default service
